package com.hlj.ncp.transaction.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hlj.ncp.common.core.domain.AjaxResult;
import com.hlj.ncp.transaction.entity.Transaction;
import com.hlj.ncp.transaction.service.ITransactionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 交易管理API控制器
 */
@RestController
@RequestMapping("/api/transaction")
public class TransactionApiController {

    @Autowired
    private ITransactionService transactionService;

    /**
     * 获取交易列表
     */
    @PostMapping("/list")
    public Map<String, Object> getTransactionList(@RequestBody Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取分页参数
            int pageSize = params.get("length") != null ? Integer.parseInt(params.get("length").toString()) : 10;
            int pageNum = params.get("start") != null ? (Integer.parseInt(params.get("start").toString()) / pageSize) + 1 : 1;
            
            // 获取查询条件
            String transactionType = params.get("transactionType") != null ? params.get("transactionType").toString() : null;
            String productName = params.get("productName") != null ? params.get("productName").toString() : null;
            String warehouseId = params.get("warehouseId") != null ? params.get("warehouseId").toString() : null;
            String status = params.get("status") != null ? params.get("status").toString() : null;
            String startDate = params.get("startDate") != null ? params.get("startDate").toString() : null;
            String endDate = params.get("endDate") != null ? params.get("endDate").toString() : null;
            
            // 构建查询条件
            LambdaQueryWrapper<Transaction> queryWrapper = new LambdaQueryWrapper<>();
            
            if (StringUtils.hasText(transactionType)) {
                queryWrapper.eq(Transaction::getTransactionType, transactionType);
            }
            
            if (StringUtils.hasText(productName)) {
                queryWrapper.like(Transaction::getProductName, productName);
            }
            
            if (StringUtils.hasText(warehouseId)) {
                queryWrapper.eq(Transaction::getWarehouseId, warehouseId);
            }
            
            if (StringUtils.hasText(status)) {
                queryWrapper.eq(Transaction::getStatus, status);
            }
            
            if (StringUtils.hasText(startDate)) {
                queryWrapper.ge(Transaction::getCreateTime, startDate + " 00:00:00");
            }
            
            if (StringUtils.hasText(endDate)) {
                queryWrapper.le(Transaction::getCreateTime, endDate + " 23:59:59");
            }
            
            // 排序
            queryWrapper.orderByDesc(Transaction::getCreateTime);
            
            // 执行分页查询
            Page<Transaction> page = new Page<>(pageNum, pageSize);
            Page<Transaction> transactionPage = transactionService.page(page, queryWrapper);
            
            // 构建返回结果
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", transactionPage.getRecords());
            result.put("recordsTotal", transactionPage.getTotal());
            result.put("recordsFiltered", transactionPage.getTotal());
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取交易列表失败: " + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取交易详情
     */
    @GetMapping("/{id}")
    public Map<String, Object> getTransaction(@PathVariable String id) {
        // 模拟数据，实际项目中应从数据库获取
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        
        data.put("transactionId", id);
        data.put("transactionType", "IN");
        data.put("productName", "大米");
        data.put("productId", "P001");
        data.put("quantity", 1000);
        data.put("unit", "kg");
        data.put("amount", 5000);
        data.put("warehouseName", "1号仓库");
        data.put("warehouseId", "W001");
        data.put("status", "COMPLETED");
        data.put("createTime", "2023-06-01 10:30:00");
        data.put("updateTime", "2023-06-01 14:20:00");
        data.put("remark", "这是一条交易备注信息，描述交易的相关详情。");
        
        result.put("code", 200);
        result.put("message", "success");
        result.put("data", data);
        
        return result;
    }
    
    /**
     * 删除交易
     */
    @DeleteMapping("/{id}")
    public Map<String, Object> deleteTransaction(@PathVariable String id) {
        // 模拟数据，实际项目中应从数据库删除
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "删除成功");
        
        return result;
    }
    
    /**
     * 完成交易
     */
    @PutMapping("/{id}/complete")
    public Map<String, Object> completeTransaction(@PathVariable String id) {
        // 模拟数据，实际项目中应更新数据库
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "操作成功");
        
        return result;
    }
    
    /**
     * 获取统计数据
     */
    @GetMapping("/statistics")
    public Map<String, Object> getStatistics(@RequestParam(required = false) String startDate,
                                            @RequestParam(required = false) String endDate) {
        // 模拟数据，实际项目中应从数据库统计
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        
        // 基础统计
        data.put("totalTransactions", 1284);
        data.put("totalAmount", 1256890);
        data.put("avgDailyTransactions", 42.8);
        data.put("growthRate", 12.5);
        
        // 交易趋势
        List<Map<String, Object>> trend = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            Map<String, Object> item = new HashMap<>();
            item.put("date", "2023-" + (i < 10 ? "0" + i : i) + "-01");
            item.put("count", 100 + new Random().nextInt(200));
            item.put("amount", 100000 + new Random().nextInt(500000));
            trend.add(item);
        }
        data.put("transactionTrend", trend);
        
        // 交易类型分布
        Map<String, Integer> typeDistribution = new HashMap<>();
        typeDistribution.put("IN", 335);
        typeDistribution.put("OUT", 310);
        typeDistribution.put("TRANSFER", 234);
        typeDistribution.put("CHECK", 135);
        data.put("transactionTypeDistribution", typeDistribution);
        
        // 产品TOP10
        List<Map<String, Object>> productTop = new ArrayList<>();
        String[] products = {"大米", "小麦", "玉米", "高粱", "大豆", "花生", "土豆", "红薯", "白菜", "萝卜"};
        for (int i = 0; i < 10; i++) {
            Map<String, Object> item = new HashMap<>();
            item.put("productName", products[i]);
            item.put("count", 300 + new Random().nextInt(100));
            item.put("amount", 1000000 + new Random().nextInt(1000000));
            productTop.add(item);
        }
        data.put("productTopList", productTop);
        
        // 仓库分布
        Map<String, Integer> warehouseDistribution = new HashMap<>();
        warehouseDistribution.put("1号仓", 335);
        warehouseDistribution.put("2号仓", 310);
        warehouseDistribution.put("3号仓", 234);
        warehouseDistribution.put("4号仓", 135);
        warehouseDistribution.put("5号仓", 1548);
        data.put("warehouseDistribution", warehouseDistribution);
        
        // 月度对比
        List<Map<String, Object>> monthlyComparison = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            Map<String, Object> item1 = new HashMap<>();
            item1.put("yearMonth", "2022-" + (i < 10 ? "0" + i : i));
            item1.put("count", 100 + new Random().nextInt(200));
            monthlyComparison.add(item1);
            
            Map<String, Object> item2 = new HashMap<>();
            item2.put("yearMonth", "2023-" + (i < 10 ? "0" + i : i));
            item2.put("count", 100 + new Random().nextInt(200));
            monthlyComparison.add(item2);
        }
        data.put("monthlyComparison", monthlyComparison);
        
        result.put("code", 200);
        result.put("message", "success");
        result.put("data", data);
        
        return result;
    }
    
    /**
     * 获取报表列表
     */
    @GetMapping("/reports")
    public Map<String, Object> getReports() {
        // 模拟数据，实际项目中应从数据库获取
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> data = new ArrayList<>();
        
        // 模拟4条报表记录
        String[] types = {"monthly", "monthly", "monthly", "quarterly"};
        String[] names = {"2023年3月交易月报", "2023年2月交易月报", "2023年1月交易月报", "2022年第四季度报表"};
        String[] ranges = {"2023-03-01 至 2023-03-31", "2023-02-01 至 2023-02-28", "2023-01-01 至 2023-01-31", "2022-10-01 至 2022-12-31"};
        String[] times = {"2023-04-01 10:30:22", "2023-03-01 09:15:47", "2023-02-01 11:05:36", "2023-01-05 14:22:10"};
        
        for (int i = 0; i < 4; i++) {
            Map<String, Object> report = new HashMap<>();
            report.put("id", "R" + (2023000 + i));
            report.put("reportName", names[i]);
            report.put("reportType", types[i]);
            report.put("timeRange", ranges[i]);
            report.put("createTime", times[i]);
            data.add(report);
        }
        
        result.put("code", 200);
        result.put("message", "success");
        result.put("data", data);
        
        return result;
    }
    
    /**
     * 生成报表
     */
    @PostMapping("/report/generate")
    public Map<String, Object> generateReport(@RequestBody Map<String, Object> params) {
        // 模拟数据，实际项目中应生成报表并保存
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        
        // 模拟报表HTML内容
        String reportHtml = "<div class=\"report-header text-center mb-4\">" +
                "<h3>交易月报表</h3>" +
                "<p class=\"text-muted\">报表周期: 2023-03-01 至 2023-03-31</p>" +
                "</div>" +
                // ... 更多HTML内容
                "<div class=\"report-footer text-right\">" +
                "<p class=\"text-muted\">报表生成时间: " + new Date() + "</p>" +
                "<p class=\"text-muted\">报表生成人: 系统管理员</p>" +
                "</div>";
        
        data.put("reportHtml", reportHtml);
        data.put("hasCharts", true);
        
        // 图表数据
        Map<String, Object> chartData = new HashMap<>();
        
        // 交易类型分布图配置
        Map<String, Object> typeChartOption = new HashMap<>();
        // ... 配置省略
        
        // 交易金额趋势图配置
        Map<String, Object> trendChartOption = new HashMap<>();
        // ... 配置省略
        
        chartData.put("typeChartOption", typeChartOption);
        chartData.put("trendChartOption", trendChartOption);
        
        data.put("chartData", chartData);
        
        result.put("code", 200);
        result.put("message", "success");
        result.put("data", data);
        
        return result;
    }
    
    /**
     * 获取报表详情
     */
    @GetMapping("/report/{id}")
    public Map<String, Object> getReport(@PathVariable String id) {
        // 与生成报表接口返回相同的模拟数据
        return generateReport(null);
    }
    
    /**
     * 删除报表
     */
    @DeleteMapping("/report/{id}")
    public Map<String, Object> deleteReport(@PathVariable String id) {
        // 模拟数据，实际项目中应从数据库删除
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "删除成功");
        
        return result;
    }
    
    /**
     * 获取产品列表
     */
    @GetMapping("/products")
    public Map<String, Object> getProducts() {
        // 模拟数据，实际项目中应从数据库获取
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> data = new ArrayList<>();
        
        // 模拟10个产品
        String[] products = {"大米", "小麦", "玉米", "高粱", "大豆", "花生", "土豆", "红薯", "白菜", "萝卜"};
        String[] units = {"kg", "kg", "kg", "kg", "kg", "kg", "kg", "kg", "个", "个"};
        
        for (int i = 0; i < products.length; i++) {
            Map<String, Object> product = new HashMap<>();
            product.put("id", 1001L + i);  // 修改为Long类型
            product.put("name", products[i]);
            product.put("unit", units[i]);
            product.put("price", 5 + new Random().nextInt(20));
            data.add(product);
        }
        
        result.put("code", 200);
        result.put("message", "success");
        result.put("data", data);
        
        return result;
    }
    
    /**
     * 获取单个产品信息
     */
    @GetMapping("/product/{id}")
    public Map<String, Object> getProduct(@PathVariable String id) {
        // 模拟数据，实际项目中应从数据库获取
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        
        // 解析ID
        Long productId;
        try {
            // 尝试直接解析为Long
            productId = Long.parseLong(id);
        } catch (NumberFormatException e) {
            // 如果是以字母开头的格式(如P1001)，则提取数字部分
            if (id.matches("[A-Za-z]\\d+")) {
                productId = Long.parseLong(id.substring(1));
            } else {
                // 无法解析的ID格式
                result.put("code", 400);
                result.put("message", "Invalid product ID format");
                return result;
            }
        }
        
        // 根据ID查找产品
        String[] products = {"大米", "小麦", "玉米", "高粱", "大豆", "花生", "土豆", "红薯", "白菜", "萝卜"};
        String[] units = {"kg", "kg", "kg", "kg", "kg", "kg", "kg", "kg", "个", "个"};
        
        int index = (int)(productId - 1001L);
        if (index >= 0 && index < products.length) {
            data.put("id", productId);
            data.put("name", products[index]);
            data.put("unit", units[index]);
            data.put("price", 5 + new Random().nextInt(20));
        }
        
        result.put("code", 200);
        result.put("message", "success");
        result.put("data", data);
        
        return result;
    }
    
    /**
     * 获取仓库列表
     */
    @GetMapping("/warehouses")
    public Map<String, Object> getWarehouses() {
        // 模拟数据，实际项目中应从数据库获取
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> data = new ArrayList<>();
        
        // 模拟5个仓库
        String[] warehouses = {"1号仓库", "2号仓库", "3号仓库", "4号仓库", "5号仓库"};
        String[] addresses = {"哈尔滨市道里区", "哈尔滨市南岗区", "哈尔滨市香坊区", "哈尔滨市道外区", "哈尔滨市平房区"};
        
        for (int i = 0; i < warehouses.length; i++) {
            Map<String, Object> warehouse = new HashMap<>();
            warehouse.put("id", 2001L + i);  // 修改为Long类型
            warehouse.put("name", warehouses[i]);
            warehouse.put("address", addresses[i]);
            warehouse.put("capacity", 1000 + i * 500);
            data.add(warehouse);
        }
        
        result.put("code", 200);
        result.put("message", "success");
        result.put("data", data);
        
        return result;
    }
    
    /**
     * 保存交易记录（新增或更新）
     */
    @PostMapping("/save")
    public Map<String, Object> saveTransaction(@RequestBody Transaction transaction) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 设置默认值
            if (transaction.getTransactionId() == null) {
                // 新增交易
                // 生成交易编号
                String transactionNo = "TX" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) + 
                                      String.format("%03d", new Random().nextInt(1000));
                transaction.setTransactionNo(transactionNo);
                
                // 设置创建时间和创建人
                transaction.setCreateTime(LocalDateTime.now());
                transaction.setCreateBy(getCurrentUsername());
            } else {
                // 更新交易
                // 先查询原有交易信息
                Transaction existingTransaction = transactionService.getById(transaction.getTransactionId());
                if (existingTransaction == null) {
                    result.put("code", 400);
                    result.put("message", "交易记录不存在");
                    return result;
                }
                
                // 保留原有的交易编号和创建信息
                transaction.setTransactionNo(existingTransaction.getTransactionNo());
                transaction.setCreateTime(existingTransaction.getCreateTime());
                transaction.setCreateBy(existingTransaction.getCreateBy());
                
                // 设置更新时间和更新人
                transaction.setUpdateTime(LocalDateTime.now());
                transaction.setUpdateBy(getCurrentUsername());
            }
            
            // 保存交易记录
            boolean success = transactionService.saveOrUpdate(transaction);
            
            if (success) {
                result.put("code", 200);
                result.put("message", "保存成功");
                result.put("data", transaction);
            } else {
                result.put("code", 500);
                result.put("message", "保存失败");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "保存失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取当前登录用户名
     */
    private String getCurrentUsername() {
        try {
            org.springframework.security.core.Authentication authentication = 
                org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication();
            if (authentication != null) {
                return authentication.getName();
            }
        } catch (Exception e) {
            // 忽略异常
        }
        return "system";
    }
} 